﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using hedefgrup.reports.renault.database;

namespace hedefgrup.reports.common
{
    public class Filter_DataColumn : Filter
    {
        private string columnName;
        private Type valueType;

        public Filter_DataColumn(DataColumn dataColumn)
        {
            columnName = dataColumn.ColumnName;
            valueType = dataColumn.DataType;
        }

        public Filter_DataColumn(string columnName, Type valueType)
        {
            this.columnName = columnName;
            this.valueType = valueType;
        }

        public override string Name
        {
            get
            {
                return columnName;
            }
        }

        public override string Expression
        {
            get { return columnName; }
        }

        public override string Operator
        {
            get { return "="; }
        }

        public override Type ValueType
        {
            get { return valueType; }
        }

        public override string[] GetValueList()
        {
            List<string> values = new List<string>();

            Criteria[] criterias = Report.Criterias.ToArray();
            List<Filter> appliedFilters = new List<Filter>(Report.GetAppliedFilters());
            
            for (int i = 0; i < appliedFilters.Count; i++)
            {
                if (appliedFilters[i] == this)
                {
                    appliedFilters.Remove(this);
                }
            }

            if (Report.Context.User != null && Report.Context.User.getAuthLevel() == "dealer")
            {
                Filter dealerCodeFilter = new Filter_DataColumn(Report.DealerColumn, typeof(string));
                dealerCodeFilter.Values.Clear();
                dealerCodeFilter.Values.AddRange(Report.Context.User.getDealerCodes());
                appliedFilters.Add(dealerCodeFilter);
            }

            DataTable valuesData = db.query
            (
                "SELECT DISTINCT TOP 1000 " + columnName + " FROM " + Context.TableName + " (NOLOCK) " +
                Report.GetSqlStatementFilter(criterias, appliedFilters.ToArray()) +
                "ORDER BY " + columnName + " ASC",
                Report.GetSqlStatementParameters(criterias, appliedFilters.ToArray())
            );

            foreach (DataRow valueRow in valuesData.Rows)
            {
                if (valueRow[columnName] != DBNull.Value)
                {
                    values.Add(valueRow[columnName].ToString());
                }
            }
            return values.ToArray();
        }
    }
}
